import sys
from time import sleep

import pygame

from alien_invasion.buttel import Buttel
from alien_invasion.alien import Alien

def check_events(ai_settings, screen, ship, bullets):
    """响应鼠标和键盘事件"""
    for event in pygame.event.get():
        if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_q) :
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                ship.moving_right = True
            elif event.key == pygame.K_LEFT:
                ship.moving_left = True
            elif event.key == pygame.K_UP:
                ship.moving_up = True
            elif event.key == pygame.K_DOWN:
                ship.moving_down = True
            elif event.key == pygame.K_SPACE:
                if len(bullets) < ai_settings.bullet_allowed:
                    new_bullet = Buttel(ai_settings,screen,ship)
                    bullets.add(new_bullet)
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_RIGHT:
                ship.moving_right = False
            elif event.key == pygame.K_LEFT:
                ship.moving_left = False
            elif event.key == pygame.K_UP:
                ship.moving_up = False
            elif event.key == pygame.K_DOWN:
                ship.moving_down = False

def update_screen(ai_settings,screen,ship,aliens, bullets):
    """更新屏幕并切换到新屏幕"""
    screen.fill(ai_settings.bg_color)

    #绘制子弹
    for bullet in bullets.sprites():
        bullet.draw_bullet()

    for alien in  aliens.sprites():
        alien.blitme()
    ship.blitme()
    aliens.draw(screen)
    # 让最近绘制的屏幕可见
    pygame.display.flip()

def update_bullets(aliens, bullets):
    """更新子弹仓库"""

    #更新子弹位置
    bullets.update()
    for bullet in bullets.copy():
        if bullet.rect.bottom <= 0:
            bullets.remove(bullet)
    collisions = pygame.sprite.groupcollide(bullets, aliens, True ,True)

def get_number_alian_x(ai_settings, alian_width):
    """获取一行外星人数量"""
    avaliable_space_x = ai_settings.screen_width - alian_width * 2
    number_alian_x = int(avaliable_space_x / (2 * alian_width))
    return number_alian_x

def get_number_alian_rows(ai_settings, ship_height, alian_height):
    """获取外星人行数"""
    avaliable_space_y = ai_settings.screen_height - alian_height * 3 - ship_height
    return int(avaliable_space_y / (alian_height * 2))

def create_alian(ai_settings, screen, alians, alian_number, row_number):
    """创建外星人"""
    alian = Alien(ai_settings, screen)
    alian_width  = alian.rect.width
    alian_height = alian.rect.height
    alian.x = alian_width + 2 * alian_width * alian_number
    alian.rect.y = alian_height + 2 * alian_height * row_number
    alian.rect.x = alian.x
    alians.add(alian)

def create_fleet(ai_settings, screen, ship, alians):
    """创建外星人群组"""
    alian = Alien(ai_settings, screen)
    alian_width = alian.rect.width
    alian_height = alian.rect.height

    number_alian_x = get_number_alian_x(ai_settings, alian_width)
    number_rows = get_number_alian_rows(ai_settings, ship.rect.height, alian_height)
    #创建一行外星人
    for row_number in  range(number_rows):
        for alian_number in range(number_alian_x):
            create_alian(ai_settings,screen,alians , alian_number, row_number)

def check_fleet_edges(ai_settings, aliens):
    for alien in  aliens.sprites():
        if alien.check_edges():
            change_fleet_direction(ai_settings, aliens)
            break

def change_fleet_direction(ai_settings, aliens):
    for alien in aliens.sprites():
        alien.rect.y += ai_settings.fleet_drop_speed
    ai_settings.fleet_direction *= -1

def update_aliens(ai_settings, stats, screen, ship, aliens ,bullets):
    check_fleet_edges(ai_settings, aliens)
    aliens.update()

    #检查外星人是否膨胀飞船
    if pygame.sprite.spritecollideany(ship, aliens):
        ship_hit(ai_settings, stats, screen, ship, aliens ,bullets)
    check_aliens_bottom(ai_settings, stats, screen, ship, aliens ,bullets)

def ship_hit(ai_settings, stats, screen, ship, aliens, bullets):
    """响应飞船被外星人撞"""

    if stats.ship_left > 0:
        # 将飞船ship_left 减少1
        stats.ship_left -= 1

        #清空外星人列表和子弹列表
        aliens.empty()
        bullets.empty()

        #创建新的外星人,并将飞船放置屏幕底部中央
        ship.center_ship()
        create_fleet(ai_settings, screen, ship, aliens)

        #暂停0.5秒
        sleep(1)
    else:
        stats.game_active = False

def check_aliens_bottom(ai_settings, stats, screen, ship, aliens, bullets):
    """检测飞船是否到达屏幕底部"""
    screen_rect = screen.get_rect()
    for alien in  aliens.sprites():
        if alien.rect.bottom >= screen_rect.bottom:
            #像飞船被撞倒一样处理
            ship_hit(ai_settings, stats, screen, ship, aliens ,bullets)
            break
